package com.neu.flashmall.ms.controller;

import com.github.pagehelper.PageInfo;
import com.neu.common.utils.ValidUtil;
import com.neu.common.valid.UpdateGroup;
import com.neu.flashmall.ms.entity.SysUser;
import com.neu.flashmall.ms.service.SysUserService;
import com.neu.common.utils.Result;
import com.neu.flashmall.ms.vo.UserVo;
import com.neu.flashmall.ms.vo.AuthorityVo;
import com.neu.flashmall.ms.vo.SysUserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
@RequestMapping("sys_user")
@Api(value = "后台管理系统用户接口")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @GetMapping(value = "/test")
    public Result test(String username,String password){
        System.out.println(username);
        System.out.println(password);
        return Result.ok();
    }

    @ApiOperation("登录方法")
    @PostMapping ("/login")
    public Result login(@ApiParam(value = "登录用户对象") @RequestBody SysUser sysUser, HttpSession session){
        String code = (String)session.getAttribute("code");
        if(code != null && code.equals(sysUser.getCheckCode())){
            String username = sysUser.getUsername();
            String password = sysUser.getPassword();
            SysUserVo sysUserVo = new SysUserVo();
            String result = this.sysUserService.login(username,password,sysUserVo);
            if(result.equals("success")){
                return Result.ok().put(sysUserVo).setMessage("登录成功");
            }else{
                return Result.error().setMessage(result);
            }
        }else{
            return Result.error().setMessage("验证码错误");
        }
    }

    @GetMapping(value = "/logout")
    @ApiOperation(value = "退出登录API，主要是用来清除redis中的token")
    public Result logout(String token){
        if(StringUtils.isEmpty(token)){
           return Result.ok().setMessage("退出登录成功");
        }
        this.sysUserService.logout(token);
        return Result.ok().setMessage("退出登录成功");
    }

    @GetMapping("/getCode")
    @ApiOperation("获取验证码接口")
    public ResponseEntity<byte[]> getCode(HttpSession session) throws IOException {
        char[] arr = {'0','1','2','3','4','5','6','7','8','9'};
        StringBuilder stb = new StringBuilder();
        int n;
        for(int i = 0;i < 4;i++) {
            n = (int)(Math.random()*arr.length);
            stb.append(arr[n]);
        }

        session.setAttribute("code", stb.toString());

        //把字符串放入到图片中，写入到输出流中
        BufferedImage buffImg = new BufferedImage(90, 20, BufferedImage.TYPE_INT_RGB);
        //得到画布
        Graphics g = buffImg.getGraphics();
        //向画布中写入字符串
        g.drawString(stb.toString(), 20, 15);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ImageIO.write(buffImg, "jpeg", bos);

        return new ResponseEntity<>(bos.toByteArray(), HttpStatus.CREATED);
    }

    @PostMapping("/checkCode")
    @ApiOperation("校验验证码接口")
    public Result checkCode(@RequestBody String checkCode, HttpSession session){
        String code = (String)session.getAttribute("code");

        if(code != null && code.equals(checkCode)){
            return Result.ok().put(true);
        }
        return Result.error().put(false);
    }

    @PostMapping("/checkPhoneAndName")
    @ApiOperation("校验联系方式接口")
    public Result checkPhone(@RequestBody UserVo userVO){
        boolean result = sysUserService.checkPhone(userVO);
        if(result){
            return Result.ok();
        }
        return Result.error().setMessage("手机号已被使用");
    }

    @PostMapping("/checkUserName")
    @ApiOperation("校验用户名接口")
    public Result checkUserName(String username){
        if(sysUserService.checkUserName(username)){
            return Result.ok().put(true);
        }
        return Result.error().put(false);
    }

    @PutMapping("/register")
    @ApiOperation("注册接口")
    public Result register(@RequestBody SysUser sysUser){
        if(sysUserService.register(sysUser) > 0){
            return Result.ok().put(true);
        }
        return Result.error();
    }

    @ApiOperation("获取用户所有信息")
    @GetMapping("/getPaged")
    public Result getPaged(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "3") int pageSize){
        PageInfo<SysUser> pageInfo = sysUserService.getPaged(pageNum,pageSize);
        return Result.ok().put(pageInfo);
    }

    @ApiOperation("删除用户信息")
    @DeleteMapping("/check/deleteSysUser")
    public Result delete(long id){
        if(sysUserService.delete(id)>0){
            return Result.ok().put(true);
        }
        return Result.error();
    }

    @ApiOperation("编辑用户信息")
    @PutMapping("/check/edit")
    public Result update(
            @Validated(value = UpdateGroup.class) @RequestBody SysUser sysUser,
            BindingResult bindingResult){
        if(bindingResult.hasErrors()){
            return ValidUtil.createResultByBindingResult(bindingResult);
        }
        if(sysUserService.update(sysUser)>0){
            return Result.ok().put(true);
        }
        return Result.error();
    }

    @ApiOperation("重置用户密码")
    @GetMapping("/check/resetPassword")
    public Result resetPassword(String username){
        System.out.println(username);
        if(sysUserService.resetPassword(username)){
            return Result.ok().put(true);
        }
        return Result.error();
    }

    @ApiOperation("修改用户密码")
    @PutMapping("/changePassword")
    public Result changePassword(@RequestBody SysUser sysUser){
        if(sysUserService.changePassword(sysUser)){
            return Result.ok().put(true);
        }
        return Result.error();
    }

    @GetMapping("/getUserByToken")
    @ApiOperation(value = "通过token获取用户信息")
    public Result getUserByToken(String token){
        SysUser sysUser = this.sysUserService.getSysUserByTokenWithRedis(token);
        if(sysUser == null){
            return Result.error();
        }
        return Result.ok().put(sysUser);
    }

    @PostMapping("/getUserAuthority")
    @ApiOperation(value = "获得某个用户的权限")
    public Result getUserAuthority(@RequestBody SysUser sysUser){
        AuthorityVo authorityVo = new AuthorityVo();
        String result = this.sysUserService.toMakeUpAuthorityVo(sysUser.getUsername(),sysUser.getPassword(),authorityVo);
        if(result.equals("获取权限成功")){
            return Result.ok().setMessage(result).put(authorityVo);
        }
        return Result.error().setMessage(result);
    }

    @GetMapping("/getUserWithAuthority")
    @ApiOperation(value = "通过token获得某个用户的权限和信息")
    public Result getUserWithAuthority(String token){
        SysUserVo sysUserVo = this.sysUserService.getUserWithAuthorityByToken(token);
        return Result.ok().put(sysUserVo);
    }

    @GetMapping("/check/changeUserStatus")
    @ApiOperation(value = "转换用户状态")
    public Result changeUserStatus(String username,Integer status){
        String result = this.sysUserService.changeUserStatus(username,status);
        if("数据库异常".equals(result)){
            return Result.error().setMessage(result);
        }
        return Result.ok().setMessage(result);
    }
}
